import numpy as np

f = open("站点信息.txt", "r", encoding='utf-8')
data = []
str = f.readlines()

for i in str:
    i = i[:-1]
    if i != '':
        data.append(i)

subwayname = []

for i in data:
    if (i[-1] == '线'):
        subwayname.append(i)

sub_line_name_and_port_name = []  # 线路的名称和线路上的站点
temp_line_and_pot = []  # 临时
index_array = []  #
for i in subwayname:
    index_array.append(data.index(i))

for i in range(len(index_array) - 1):
    temp_line_and_pot = data[index_array[i]:index_array[i + 1]]
    sub_line_name_and_port_name.append(temp_line_and_pot)

temp_line_and_pot = data[index_array[len(index_array) - 1]:]
sub_line_name_and_port_name.append(temp_line_and_pot)

new_sub_line_name_and_port_name = []

for i in sub_line_name_and_port_name:
    temp_line_and_pot = []
    k = i[0]
    i = i[1:]
    temp_line_and_pot.append(k)
    temp_line_and_pot.append(i)
    new_sub_line_name_and_port_name.append(temp_line_and_pot)

f.close()


# for i in new_sub_line_name_and_port_name:
#     print(i[0])
#     print()
#     for k in i[1]:
#         print(k,end=" ")
#     print()

from py2neo import Graph, Node, Relationship, NodeMatcher
from py2neo.matching import *

graph = Graph("bolt://localhost:7687", auth=("neo4j", "liangn"))
matcher = NodeMatcher(graph)

graph.run("match (n) detach delete n")

for i in new_sub_line_name_and_port_name:
    # print(i[0])
    node = Node("地铁线路", name=i[0])
    graph.create(node)

for i in new_sub_line_name_and_port_name:
    node_piror = None
    for i2 in i[1]:
        node=matcher.match('站点', name=i2).first()
        #node["所属线路"] = i1  # 添加地铁所属线路标签
        if node==None:
            node = Node("站点",name=i2)
            #node = Node("站点", name=i2, 所属线路=i1)
            graph.create(node)
        if node_piror!=None:
            ab=Relationship(node_piror,"相邻",node)
            graph.create(ab)
        node_piror=node


for i in new_sub_line_name_and_port_name:
    for i2 in i[1]:
        a_have = graph.nodes.match("地铁线路", name=i[0]).first()
        b_have = graph.nodes.match("站点", name=i2).first()
        rel_a = Relationship(b_have, "位于", a_have)
        graph.create(rel_a)





